package com.rabbit.eap.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbit.eap.framework.aspectj.annotation.DataScope;
import com.rabbit.eap.framework.common.api.ApiResult;
import com.rabbit.eap.framework.common.enums.MsgEnum;
import com.rabbit.eap.framework.common.service.impl.BaseServiceImpl;
import com.rabbit.eap.framework.convert.BeanConverter;
import com.rabbit.eap.framework.core.pagination.PageInfo;
import com.rabbit.eap.framework.core.pagination.Paging;
import com.rabbit.eap.system.domain.TreeSelect;
import com.rabbit.eap.system.dto.SysDeptDTO;
import com.rabbit.eap.system.entity.SysDept;
import com.rabbit.eap.system.entity.SysUser;
import com.rabbit.eap.system.entity.SysUserDept;
import com.rabbit.eap.system.mapper.SysDeptMapper;
import com.rabbit.eap.system.mapper.SysUserDeptMapper;
import com.rabbit.eap.system.mapper.SysUserMapper;
import com.rabbit.eap.system.param.SysDeptPageParam;
import com.rabbit.eap.system.service.ISysDeptService;
import com.rabbit.eap.system.vo.SysDeptVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: eap
 * @packageName: com.rabbit.eap.system.service.impl
 * @className SysDeptServiceImpl
 * @author： rabbit
 * @version： 1.0
 * @since： 2020/06/06 23:34:02
 * <p>Description:
 * 部门表 服务实现类
 * </p>

 */
@Slf4j
@Service
public class SysDeptServiceImpl extends BaseServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * @param sysDeptDTO:sysDeptDTO数据传输对象
     * @throws Exception
     * @Description: 添加部门表
     * @methodName: saveSysDept
     * @return: ApiResult
     * @date: 2020/06/06 23:34:02
     * @author: rabbit
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult saveSysDept(SysDeptDTO sysDeptDTO) throws Exception {
        boolean flag = checkDeptNameUnique(sysDeptDTO);
        if (flag) {
            return ApiResult.ok(sysDeptDTO.getDeptName() + MsgEnum.IS_EXIST.getDesc());
        }
        if (sysDeptDTO.getParentId() > 0) {
            //如果父节点为不正常状态,则不允许新增子节点
            SysDept info = sysDeptMapper.selectOne(
                    new QueryWrapper<SysDept>().lambda().eq(SysDept::getId, sysDeptDTO.getParentId())
            );
            if (!info.getStatus().equals(StringPool.ZERO)) {
                return ApiResult.fail(MsgEnum.DEPT_DISABLE.getDesc());
            }
            String ancestorsId = info.getAncestors() + StringPool.COMMA + sysDeptDTO.getParentId();
            String ancestorsName = getAncestorsName(ancestorsId);
            sysDeptDTO.setAncestors(ancestorsId);
            sysDeptDTO.setAncestorsName(ancestorsName);
        } else {
            sysDeptDTO.setAncestors(StringPool.ZERO);
            sysDeptDTO.setAncestorsName(StringPool.DASH);
        }
        SysDept sysDept = sysDeptDTO.convert(SysDept.class);
        boolean bool = super.save(sysDept);
        if (bool) {
            return ApiResult.ok(MsgEnum.ADD_SUCCESS.getDesc());
        } else {
            return ApiResult.fail(MsgEnum.ADD_FAIL.getDesc());
        }
    }

    /**
     * @param sysDeptDTO:sysDeptDTO数据传输对象
     * @throws Exception
     * @Description 修改部门表
     * @methodName: modifySysDept
     * @return: ApiResult
     * @date: 2020/06/06 23:34:02
     * @author: rabbit
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult modifySysDept(SysDeptDTO sysDeptDTO) throws Exception {
        boolean flag = checkDeptNameUnique(sysDeptDTO);
        if (flag) {
            return ApiResult.ok(sysDeptDTO.getDeptName() + MsgEnum.IS_EXIST.getDesc());
        }
        /*if (sysDeptDTO.getParentId().equals(sysDeptDTO.getId())) {
            return ApiResult.fail("修改部门'" + sysDeptDTO.getDeptName() + "'失败，上级部门不能是自己");
        }*/
        if (sysDeptDTO.getParentId() > 0) {
            SysDept newParentDept = sysDeptMapper.selectOne(
                    new QueryWrapper<SysDept>().lambda().eq(SysDept::getId, sysDeptDTO.getParentId())
            );
            SysDept oldDept = sysDeptMapper.selectById(sysDeptDTO.getId());
            if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
                String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
                String oldAncestors = oldDept.getAncestors();
                String ancestorsName = getAncestorsName(newAncestors);
                sysDeptDTO.setAncestors(newAncestors);
                sysDeptDTO.setAncestorsName(ancestorsName);
                updateDeptChildren(sysDeptDTO.getId(), newAncestors, oldAncestors);
            }
        } else {
            sysDeptDTO.setAncestors(StringPool.ZERO);
            sysDeptDTO.setAncestorsName(StringPool.DASH);
        }
        SysDept sysDept = sysDeptDTO.convert(SysDept.class);
        boolean bool = super.updateById(sysDept);
        if (bool) {
            return ApiResult.ok(MsgEnum.UPDATE_SUCCESS.getDesc());
        } else {
            return ApiResult.fail(MsgEnum.UPDATE_FAIL.getDesc());
        }
    }

    /**
     * @param deptId:部门Id
     * @throws Exception
     * @Description 删除部门表
     * @methodName: removeSysDept
     * @return: ApiResult
     * @date: 2020/06/06 23:34:02
     * @author: rabbit
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult removeSysDept(Long deptId) throws Exception {
        if (ObjectUtil.isNull(deptId)) {
            return ApiResult.fail(MsgEnum.PARAM_NOT_NULL.getDesc());
        }
        //判断是否存在子部门
        int count = sysDeptMapper.selectCount(
                new QueryWrapper<SysDept>().lambda().eq(SysDept::getParentId, deptId)
        );
        if (count > 0) {
            return ApiResult.fail(MsgEnum.HAS_DEPT_CHILD.getDesc());
        }
        //判断部门是否绑定用户
        int cnt = sysUserMapper.selectCount(
                new QueryWrapper<SysUser>().lambda().eq(SysUser::getDeptId, deptId)
        );
        int userDeptCount = sysUserDeptMapper.selectCount(
                new QueryWrapper<SysUserDept>().lambda().eq(SysUserDept::getDeptId, deptId)
        );
        boolean flag = cnt > 0 || userDeptCount > 0;
        if (flag) {
            return ApiResult.fail(MsgEnum.HAS_DEPT_USERS.getDesc());
        }
        //执行删除逻辑
        boolean bool = super.removeById(deptId);
        if (bool) {
            return ApiResult.ok(MsgEnum.DELETE_SUCCESS.getDesc());
        } else {
            return ApiResult.fail(MsgEnum.DELETE_FAIL.getDesc());
        }
    }

    /**
     * @param id: id
     * @throws Exception
     * @Description 根据Id获取部门表详情
     * @methodName: getSysDeptInfo
     * @return: ApiResult
     * @date: 2020/06/06 23:34:02
     * @author: rabbit
     */
    @Override
    public ApiResult getSysDeptById(Long id) throws Exception {
        if (ObjectUtil.isNull(id)) {
            return ApiResult.fail(MsgEnum.PARAM_NOT_NULL.getDesc());
        }
        SysDept sysDept = super.getById(id);
        SysDeptVO sysDeptVO = sysDept.convert(SysDeptVO.class);
        return ApiResult.ok(sysDeptVO);
    }

    /**
     * @param sysDeptPageParam
     * @throws Exception
     * @Description 部门表分页列表
     * @methodName: getSysDeptPageList
     * @return: ApiResult
     * @date: 2020/06/06 23:34:02
     * @author: rabbit
     */
    @Override
    public ApiResult getSysDeptPageList(SysDeptPageParam sysDeptPageParam) throws Exception {
        Page<SysDeptVO> page = new PageInfo<>(sysDeptPageParam, OrderItem.desc("create_time"));
        IPage<SysDeptVO> iPage = sysDeptMapper.getSysDeptPageList(page, sysDeptPageParam);
        Paging<SysDeptVO> paging = new Paging<SysDeptVO>(iPage);
        return ApiResult.ok(paging);
    }

    /**
     * @param dept: 部门信息
     * @Description: 校验部门名称是否唯一
     * @methodName: checkDeptNameUnique
     * @return: boolean
     * @date: 2020/6/17 19:49
     * @author: rabbit
     */
    public boolean checkDeptNameUnique(SysDeptDTO dept) {
        Long deptId = ObjectUtil.isNull(dept.getId()) ? -1L : dept.getId();
        SysDept sysDept = sysDeptMapper.selectOne(
                new QueryWrapper<SysDept>().lambda().eq(SysDept::getDeptName, dept.getDeptName())
                        .eq(SysDept::getParentId, dept.getParentId())

        );
        if (ObjectUtil.isNotNull(sysDept) && sysDept.getId().longValue() != deptId.longValue()) {
            return true;
        }
        return false;
    }

    /**
     * @param ancestorsId: 祖先id集合
     * @Description: 获取祖先名称
     * @methodName: getAncestorsName
     * @return: java.lang.String
     * @date: 2020/6/19 21:09
     * @author: rabbit
     */
    private String getAncestorsName(String ancestorsId) {
        List<String> list = Arrays.asList(ancestorsId.split(StringPool.COMMA));
        String ancestorsName = sysDeptMapper.getAncestorsName(list);
        return ancestorsName;
    }

    /**
     * @param deptId:       被修改的部门ID
     * @param newAncestors: 新的父ID集合
     * @param oldAncestors: 旧的父ID集合
     * @Description: 修改子元素关系
     * @methodName: updateDeptChildren
     * @return: void
     * @date: 2020/6/19 20:59
     * @author: rabbit
     */
    private void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = sysDeptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            String ancestorsId = child.getAncestors().replace(oldAncestors, newAncestors);
            String ancestorsName = getAncestorsName(ancestorsId);
            child.setAncestors(ancestorsId);
            child.setAncestorsName(ancestorsName);
        }
        if (children.size() > 0) {
            sysDeptMapper.updateDeptChildren(children);
        }
    }

    /**
     * @param sysDeptPageParam:
     * @Description: 获取部门列表
     * @methodName: getSysDeptList
     * @return: com.rabbit.eap.framework.common.api.ApiResult
     * @date: 2020/6/26 20:18
     * @author: rabbit
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> getSysDeptList(SysDeptPageParam sysDeptPageParam) {
        List<SysDept> list = sysDeptMapper.getSysDeptList(sysDeptPageParam);
        return list;
    }

    /**
     * @param sysDeptPageParam:
     * @Description: 获取部门下拉树列表
     * @methodName: getDeptTree
     * @return: java.util.List<com.rabbit.eap.system.domain.TreeSelect>
     * @date: 2020/6/26 21:09
     * @author: rabbit
     */
    @Override
    public List<TreeSelect> getDeptTree(SysDeptPageParam sysDeptPageParam) {
        List<SysDept> list = getSysDeptList(sysDeptPageParam);
        return buildDeptTreeSelect(list);
    }

    /**
     * @param depts: 部门列表
     * @Description: 构建前端所需要下拉树结构
     * @methodName: buildDeptTreeSelect
     * @return: java.util.List<com.rabbit.eap.system.domain.TreeSelect> 树结构列表
     * @date: 2020/6/26 21:12
     * @author: rabbit
     */
    private List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * @param depts: 部门列表
     * @Description: 构建前端所需要树结构
     * @methodName: buildDeptTree
     * @return: java.util.List<com.rabbit.eap.system.entity.SysDept> 树结构列表
     * @date: 2020/6/26 21:12
     * @author: rabbit
     */
    private List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * @param list: 部门列表
     * @param t:    部门
     * @Description: 递归获取部门
     * @methodName: recursionFn
     * @return: void
     * @date: 2020/6/26 21:15
     * @author: rabbit
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext()) {
                    SysDept n = (SysDept) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (ObjectUtil.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * @param roleId:
     * @Description: 获取对应角色部门列表树
     * @methodName: getRoleDeptTree
     * @return: com.rabbit.eap.framework.common.api.ApiResult
     * @date: 2020/6/26 21:40
     * @author: rabbit
     */
    @Override
    public ApiResult getRoleDeptTree(Long roleId) {
        List<SysDept> list = getSysDeptList(new SysDeptPageParam());
        List<Integer> checkedKeys = getDeptListByRoleId(roleId);
        Map<String, Object> map = new HashMap<>(16);
        map.put("checkedKeys", checkedKeys);
        map.put("deptList", list);
        return ApiResult.okMap("data", map);
    }

    /**
     * @param roleId:
     * @Description: 获取角色部门列表
     * @methodName: getDeptListByRoleId
     * @return: java.util.List<java.lang.Integer>
     * @date: 2020/6/26 21:43
     * @author: rabbit
     */
    private List<Integer> getDeptListByRoleId(Long roleId) {
        List<Integer> list = sysDeptMapper.getDeptListByRoleId(roleId);
        return list;
    }

    @Override
    public List<SysDeptVO> getSysDeptAll(SysDeptPageParam sysDeptPageParam) {
        LambdaQueryWrapper<SysDept> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(sysDeptPageParam.getDeptName()), SysDept::getDeptName, sysDeptPageParam.getDeptName())
                .eq(ObjectUtil.isNotNull(sysDeptPageParam.getParentId()), SysDept::getParentId, sysDeptPageParam.getParentId())
                .eq(StringUtils.isNotBlank(sysDeptPageParam.getStatus()), SysDept::getStatus, sysDeptPageParam.getStatus())
                .orderByDesc(SysDept::getSort);
        List<SysDept> list = sysDeptMapper.selectList(lambdaQueryWrapper);
        List<SysDeptVO> list1 = BeanConverter.convert(SysDeptVO.class, list);
        return list1;
    }

    /**
     * @param roleId:
     * @Description: 获取数据权限
     * @methodName: getRoleDept
     * @return: com.rabbit.eap.framework.common.api.ApiResult
     * @date: 2020/10/6 21:52
     * @author: rabbit
     */
    @Override
    public ApiResult getRoleDept(Long roleId) {
        if(ObjectUtil.isNull(roleId)){
            return ApiResult.fail(MsgEnum.PARAM_NOT_NULL.getDesc());
        }
        Set<String> set = sysDeptMapper.getRoleDept(roleId);
        return ApiResult.ok(set);
    }
}
